package com.sky.Interceptor;


import com.sky.context.BaseContext;
import com.sky.exception.BaseException;
import com.sky.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sky.utils.JwtUtils;

import java.util.Enumeration;

@Configuration
@Slf4j
public class JWTWebInterceptor implements HandlerInterceptor {
    @Autowired
    public JwtProperties jwtProperties;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入了jwt拦截器");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 获取前端返回的token
        String token = request.getHeader("token");

        log.info("token:{}",token);
        if(token == null){
            log.info("token为空");
            response.setStatus(401);
            return true;
        }
        // 开始校验token值
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtils.parseJWT(token,jwtProperties.getAdminSecretKey());
            Long empId =Long.valueOf(claims.get("empId").toString());
            log.info("当前员工id：{}", empId);
            // 将id保存到当前线程池
            BaseContext.setCurrentId(empId);
            //3、通过，放行
            return true;
        }catch (Exception e){
            //4、不通过，响应401状态码
            response.setStatus(401);
            throw new BaseException(e.getMessage());
//            return false;
        }
    }


}
